<template>
  <div class="app-container">
    <el-card>
      <!--用户数据-->
      <el-form :model="queryParams" ref="queryForm" size="small" label-width="120px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="实践课程名称">
              <el-input v-model.trim="queryParams.name" placeholder="输入内容" clearable @keyup.enter.native="handleQuery"
                @input="getList" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label-width="20px">
              <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['project:semester:add']">新增</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="tableList">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="实践课程名称" align="center" prop="name" />
        <el-table-column label="图标" align="center" prop="imageUrl">
          <template slot-scope="scope">
            <!-- <image-preview :src="scope.row.imageUrl" :width="50" :height="50" /> -->
            <el-image style="width: 50px;" :src="scope.row.imageUrl">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="name1">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.state" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.createTime.slice(0, 10) }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="创建人" align="center" prop="endTime" /> -->
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" @click="handleUpdate(scope.row)" v-hasPermi="['project:semester:edit']">编辑</el-button>
            <el-button style="color: #f56c6c;" type="text" @click="handleDelete(scope.row)"
              v-hasPermi="['project:semester:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="40%">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="实践课程名称: " prop="name">
              <el-input v-model="form.name" placeholder="请输入">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择图标：" prop="imageUrl">
              <div class="selectIcon">
                <el-image style="width: 50px;height: 50px;" :src="form.imageUrl">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
              <!-- <div class="choiceIcon">
                <el-image style="width: 60px;height: 60px;" :src="item.url" v-for="item in iconList" :key="item.url"
                  v-if="form.imageUrl != item.url" @click="changeImg(item)">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div> -->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="默认图标：" prop="expTypeIco">
              <div class="choiceIcon">
                <el-image style="width: 60px;height: 60px;" :src="item.url" v-for="item in iconList" :key="item.url"
                  v-if="form.imageUrl != item.url" @click="changeImg(item)">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="自定义图标：" prop="expTypeIco">
              <div class="choiceIcon">
                <el-upload ref="fileUpload" list-type="picture-card" :action="uploadFileUrl" :limit="1" :headers="headers"
                  :on-error="handleUploadError" :on-remove="handleDeleteFile" :file-list="fileList"
                  :on-success="handleUploadSuccess" :before-upload="beforeUpload">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态:">
              <el-radio-group v-model="form.state">
                <el-radio label="0">停用</el-radio>
                <el-radio label="1">启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import laodong from '@/assets/typeDictionary/laodong.png';
import sizheng from '@/assets/typeDictionary/sizheng.png';
import chuangxin from '@/assets/typeDictionary/chuangxin.png';
import suzhi from '@/assets/typeDictionary/suzhi.png';
import yingji from '@/assets/typeDictionary/yingji.png';
import { typeCongfigList, typeCongfigAdd, typeCongfigPut, typeCongfigDele } from "@/api/semesManage";
export default {
  name: "typeDictionary",
  data() {
    return {
      loading: false,
      total: 0,
      tableList: [],
      title: "",
      open: false,
      form: {
        state: '0'
      },
      rules: {
        name: [
          { required: true, message: '类型名称不得为空', trigger: 'blur' },
        ],
        imageUrl: [
          { required: true, message: '请设置图标', trigger: 'change' },
        ],
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      iconList: [],
      imageUrlName: 'laodong',
      headers: {
        Authorization: "Bearer " + sessionStorage.getItem("token"),
      },
      uploadFileUrl: process.env.VUE_APP_BASE_FILE + "/utils/ossUpload", // 上传文件服务器地址
      fileList: []
    };
  },
  watch: {},
  created() {
    this.getList();
    this.iconList = [
      { name: 'laodong', url: laodong },
      { name: 'sizheng', url: sizheng },
      { name: 'chuangxin', url: chuangxin },
      { name: 'suzhi', url: suzhi },
      { name: 'yingji', url: yingji },
    ];
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.tableList = [];
      this.loading = true;
      typeCongfigList({ ...this.queryParams }).then(res => {
        res.rows.forEach(v => {
          this.tableList.push({ ...v, imageUrlName: v.imageUrl, imageUrl: this.iconList.find(urls => urls.name == v.imageUrl) ? this.iconList.find(urls => urls.name == v.imageUrl).url : process.env.VUE_APP_BASE_FILE + v.imageUrl, state: String(v.state) })
        });
        this.total = res.total;
        this.loading = false;
      });
    },
    changeImg(url) {
      if (this.fileList.length > 0) {
        this.$modal
          .confirm('选择默认图标，自定义图标需重新上传，是否确定切换?')
          .then(() => {
            this.fileList = [];
            this.form.imageUrl = url.url;
            this.imageUrlName = url.name;
          })
          .catch(() => { });
      } else {
        this.form.imageUrl = url.url;
        this.imageUrlName = url.name;
      }
    },
    async handleStatusChange(row) {
      this.$modal
        .confirm('注: 启用或停用该类型需重新设置对应教师权限!')
        .then(function () {
          return typeCongfigPut({ ...row, imageUrl: row.imageUrlName, state: row.state == 1 ? 1 : 0 });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("设置成功");
        })
        .catch(() => {
          row.state = row.state == 0 ? '1' : '0';
        });
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.fileList = [{ name: res.originalFilename, url: process.env.VUE_APP_BASE_FILE + res.url, imageUrl: res.url }];
      this.form.imageUrl = process.env.VUE_APP_BASE_FILE + res.url;
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isCorrectExtension = file.name.endsWith('.jpeg') || file.name.endsWith('.png') || file.name.endsWith(('.jpg') || file.name.endsWith('.gif'));
      if (!isImage) {
        this.$message.error('上传文件不是图片!');
      }
      if (!isCorrectExtension) {
        this.$message.error('上传图片格式不正确!');
      }
      return isImage && isCorrectExtension;
    },
    // 删除文件
    handleDeleteFile(item) {
      const itemIndex = this.fileList.findIndex(file => file.name === item.name);
      this.fileList.splice(itemIndex, 1);
      this.form.imageUrl = laodong;
      this.imageUrlName = 'laodong';
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    handleAdd() {
      this.title = "新增实践课程";
      this.resetForm("form");
      this.form = {
        name: '',
        imageUrl: laodong,
        state: '0'
      };
      this.fileList = [];
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = "编辑实践课程";
      this.resetForm("form");
      this.form = { ...row };
      this.fileList = [];
      if (this.form.imageUrlName != "laodong" && this.form.imageUrlName != 'sizheng' && this.form.imageUrlName != 'chuangxin' && this.form.imageUrlName != 'suzhi' && this.form.imageUrlName != 'yingji') {
        this.fileList = [{ url: this.form.imageUrl, imageUrl: this.form.imageUrlName }];
      }
      this.$forceUpdate();
      this.open = true;
    },
    cancel() {
      this.open = false;
      this.form = {};
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryForm");
      this.getList();
    },
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除"' + row.name + '"数据项？')
        .then(function () {
          return typeCongfigDele(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 提交按钮 */
    submitForm() {
      const msgType = this.form.id >= 0 ? "编辑成功" : "新增成功";
      const urlType = this.form.id >= 0 ? typeCongfigPut : typeCongfigAdd;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const imageUrl = this.fileList.length > 0 ? this.fileList[0].imageUrl : this.imageUrlName;
          urlType({ ...this.form, imageUrl, state: Number(this.form.state) }).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess(msgType);
              this.form = {};
              this.getList();
              this.open = false;
            }
          })
        }
      })
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-dialog__body {
  .spanMa {
    margin-left: 5px;
    margin-right: 5px;
  }

  .el-select {
    width: 20% !important;
  }

  .el-date-editor {
    width: 80% !important;
  }
}

.selectIcon {
  border: 1px solid #e3e6ec;
  // border-bottom: 0;
  padding: 0 5px;
  height: 60px;
  line-height: 60px;

  .el-image {
    padding-top: 2px;
  }
}

.choiceIcon {
  border: 1px solid #e3e6ec;
  padding: 5px;
  display: flex !important;
  width: 100%;

  .el-image {
    margin: 5px 10px;
  }
}

::v-deep .el-upload-list__item-thumbnail {
  padding: 5px !important;
}

::v-deep .el-upload-list__item {
  width: 80px !important;
  height: 80px !important;
  margin-bottom: -15px !important;
}

::v-deep .el-upload--picture-card {
  width: 80px !important;
  height: 80px !important;
  line-height: 80px !important;
}

::v-deep .el-icon-close-tip {
  display: none !important;
}
</style>
